/**
 * 保养记录
 */

import React, { useState, useCallback, useEffect, useMemo } from 'react';
import {
    Card,
    Form,
    Button,
    DatePicker,
    Input,
    Tabs,
    Modal,
    message,
} from 'antd';

import { get } from '../../axios/http';
import { convertRes2Blob, formatTime, BasicTable } from '../../utils/x.js';

import { euqApplicationName } from '../../config';
const { RangePicker } = DatePicker;
const { TabPane } = Tabs;
// const { Option } = Select;


/**
 * 表格
 */
function MaintenanceLogsTable1({ data, selectedKeys, pagination, loading, onEvent }) {
    const tableColumns = [
        {
            title: '保养单号',
            dataIndex: 'maintainCode',
        },
        {
            title: '设备编号',
            dataIndex: 'equipmentCode',
        },
        {
            title: '设备名称',
            dataIndex: 'equipmentName',
        },
        {
            title: '规格型号',
            dataIndex: 'equipmentSpecsModel',
        },
        {
            title: '使用部门',
            dataIndex: 'equipmentDepart',
        },
        {
            title: '保养开始时间',
            dataIndex: 'maintainStartTime',
        },
        {
            title: '保养结束时间',
            dataIndex: 'maintainEndTime',
        },
        {
            title: '保养用时',
            dataIndex: 'wastedTime',
        },
        {
            title: '保养费用',
            dataIndex: 'maintainCost',
        },
    ];
    const tableRowSelection = {
        selectedRowKeys: selectedKeys,
        onChange: (selectedRowKeys, selectedRows) => {
            onEvent && onEvent({ type: 'UPDATE_SELECTED', keys: selectedRowKeys, rows: selectedRows });
        },
    };

    return (
        <BasicTable rowKey="id" dataSource={data} columns={tableColumns} rowSelection={tableRowSelection} pagination={pagination} loading={loading} />
    );
}

/**
 * 标签
 */
function MaintenanceLogsTabs1({ children, onEvent }) {
    const handleExtraClick = useCallback((e) => {
        onEvent && onEvent(e.currentTarget.getAttribute('data-action'));
    }, [onEvent]);

    const extraContent = (
        <div>
            <Button icon="edit" type="danger" style={{ marginLeft: 5 }} data-action="delete" onClick={handleExtraClick}>删除</Button>
            <Button icon="edit" type="default" style={{ marginLeft: 5 }} data-action="export" onClick={handleExtraClick}>导出</Button>
        </div>
    );

    return (
        <Tabs tabBarExtraContent={extraContent}>
            <TabPane tab="保养记录" key="1">
                {children}
            </TabPane>
        </Tabs>
    );
}

/**
 * 搜索表单
 */
function MaintenanceLogsForm1({ form, form: { getFieldDecorator }, onSubmit }) {
    const handleSubmit = useCallback((e) => {
        e.preventDefault();
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            onSubmit && onSubmit(values);
        });
    }, [onSubmit]);

    return (
        <Form layout="inline" onSubmit={handleSubmit}>
            <Form.Item label="保养时间">
                {getFieldDecorator('queryTime')(
                    <RangePicker />
                )}
            </Form.Item>
            <Form.Item label="保养单号">
                {getFieldDecorator('maintainCode')(
                    <Input />
                )}
            </Form.Item>
            <Form.Item>
                <Button type="primary" htmlType="submit">搜索</Button>
            </Form.Item>
        </Form>
    );
}

/**
 * 主组件
 */
function MaintenanceLogs() {
    const [data, setData] = useState([]);
    const [dataQuery, setDataQuery] = useState({});
    const [isDataLoading, setIsDataLoading] = useState(false);
    const [pagination, setPagination] = useState({});

    const [selected1, setSelected1] = useState({ key: [], row: [] });

    const fetchData = useCallback((params = {}, exact = false) => {
        setDataQuery(exact ? params : prev => ({
            ...prev,
            ...params,
        }));
    }, []);

    const exportExcel = useCallback((list = []) => {
        (async () => {
            try {
                const reqData = list.map(item => `idList=${item}`).join('&');
                const url = list.length === 0 ? euqApplicationName + '/equipmentMaintainRecord/exportEquipmentMaintainRecordExcel' : `${euqApplicationName}/equipmentMaintainRecord/exportEquipmentMaintainRecordExcel?${reqData}`;
                const res = await get(url, { responseType: 'blob' });
                convertRes2Blob(res, '保养记录');
            } catch (err) {
                Modal.error({
                    title: '发生了错误',
                    content: err.message,
                });
                console.error(err);
            }
        })();
    }, []);

    const Form1Wrap = useMemo(() => {
        return Form.create()(MaintenanceLogsForm1);
    }, []);

    const handleForm1Submit = useCallback((values) => {
        const reqData = {
            maintainCode: values.maintainCode,
        };
        if (values.queryTime && values.queryTime.length > 0) {
            reqData.startTime = formatTime(values.queryTime[0]);
            reqData.endTime = formatTime(values.queryTime[1]);
        }
        setDataQuery(reqData);
    }, []);

    const handleTabs1Event = useCallback((action) => {
        switch (action) {
            case 'delete': {
                if (selected1.key.length < 1) {
                    Modal.warn({
                        title: '至少需要选择一个项目',
                    });
                    return;
                }
                Modal.error({
                    title: '你确定要删除这些项目吗？',
                    onOk() {
                        (async () => {
                            try {
                                const reqData = {
                                    ids: selected1.key.join(','),
                                };
                                // console.log(reqData); return;
                                const res = await get(`${euqApplicationName}/equipmentMaintainRecord/equipmentMaintainRecord/${reqData.ids}`);
                                message.info('删除成功');
                                setSelected1({ key: [], row: [] });
                                fetchData();
                            } catch (err) {
                                Modal.error({
                                    title: '发生了错误',
                                    content: err.message,
                                });
                            }
                        })();
                    },
                });
                break;
            }
            case 'export': {
                if (selected1.key.length < 1) {
                    Modal.confirm({
                        title: '当前没有选择项目，将会导出所有数据。是否继续？',
                        onOk() {
                            exportExcel();
                        },
                    });
                } else {
                    exportExcel(selected1.key);
                }
                break;
            }
        }
    }, [selected1]);

    const handleTable1Event = useCallback((e) => {
        switch (e.type) {
            case 'UPDATE_SELECTED': {
                setSelected1({ key: e.keys, row: e.rows });
                break;
            }
        }
    }, []);

    useEffect(() => {
        (async () => {
            setIsDataLoading(true);
            try {
                const res = await get(euqApplicationName + '/equipmentMaintainRecord/findEquipmentMaintainRecord', { params: dataQuery });
                res && setData(res.data);
                setPagination({
                    current: res.pageNum,
                    pageSize: res.pageSize,
                    total: res.total,
                    onChange(page) {
                        setDataQuery(prev => ({
                            ...prev,
                            pageNum: page,
                        }));
                    },
                });
            } catch (err) {}
            setIsDataLoading(false);
        })();
    }, [dataQuery]);

    return (
        <>
            <Card size="small" style={{ marginBottom: 10 }}>
                <Form1Wrap onSubmit={handleForm1Submit} />
            </Card>
            <Card size="small">
                <MaintenanceLogsTabs1 onEvent={handleTabs1Event}>
                    <MaintenanceLogsTable1 data={data} selectedKeys={selected1.key} pagination={pagination} loading={isDataLoading} onEvent={handleTable1Event} />
                </MaintenanceLogsTabs1>
            </Card>
        </>
    )
}

export default MaintenanceLogs;
